package tools

import (
	"encoding/json"
	"time"

	"github.com/gogf/gf/errors/gerror"
	"github.com/golang-jwt/jwt"
)

const SECRET = "MDeDnKUrDQzfmvVsTJno1Ob4mPTekUoSphSsaeymXBM"
const Chat_sercret = "base64:MDeDnKUrDQzfmvVsTJno1Ob4mPTekUoSphSsaeymXBM="

//jwt解析 token
func JwtParseToken(tokenString string) (map[string]interface{}, error) {

	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return []byte(Chat_sercret), nil

	})
	if token == nil {
		return nil, gerror.New("token错误")
	}

	finToken := token.Claims.(jwt.MapClaims)

	return finToken, err

}
func JwtMakeToken(obj map[string]interface{}) (string, error) {
	jti, _ := json.Marshal(obj)
	claims := jwt.StandardClaims{
		Id:        string(jti),
		ExpiresAt: time.Now().Add(30 * 24 * time.Hour * time.Duration(1)).Unix(),
		IssuedAt:  time.Now().Unix(),
		NotBefore: time.Now().Unix(),
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString([]byte(Chat_sercret))
	return tokenString, err
}

func MakeToken(obj map[string]interface{}) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims(obj))
	tokenString, err := token.SignedString([]byte(SECRET))
	return tokenString, err
}

func ParseToken(tokenStr string) map[string]interface{} {
	token, _ := jwt.Parse(tokenStr, func(token *jwt.Token) (i interface{}, e error) {
		return []byte(SECRET), nil
	})

	finToken := token.Claims.(jwt.MapClaims)
	return finToken
}
